<html>
<head>
  <!-- Load Cube API library (UMD version for in-browser use) -->
  <script type="text/javascript" src="https://unpkg.com/@cubejs-client/core@0.28.38/dist/cubejs-client-core.umd.js"></script>

  <!-- Load Google Charts API -->
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

  <script type="text/javascript">
    // Cube API token and host.
    // Change to "http://localhost:4000" to use your own Cube.
    // See the docs to learn more about authentication: https://cube.dev/docs/security
    const cubeToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjEwMDAwMDAwMDAsImV4cCI6NTAwMDAwMDAwMH0.OHZOpOBVKr-sCwn8sbZ5UFsqI3uCs6e4omT7P6WVMFw";
    const cubeHost = "https://heavy-lansford.gcp-us-central1.cubecloudapp.dev";

    // Instantiate Cube API client
    const cubeApi = cubejs(cubeToken, { apiUrl: cubeHost + "/cubejs-api/v1" });

    // Load Google Charts API and packages ('corechart' is the main one)
    google.charts.load('current', { packages: [ 'corechart', 'table' ]});

    // Set a callback to run when the Google Visualization API is loaded
    google.charts.setOnLoadCallback(drawCharts);

    // Function that creates the charts.
    // We'll start with just a couple of them
    function drawCharts() {
      drawChartForArtworkArtists();
      drawChartForArtworkYears();
    }

    // Function that creates a table chart.
    // See the docs to learn more: https://developers.google.com/chart/interactive/docs/gallery/table
    function drawChartForArtworkArtists() {
      // Cube query that will fetch:
      // — artists' names (1)
      // — count of artworks for each artist (2)
      // — but only for those artworks that are labeled as paintings (3)
      // Learn more about query format in the docs: https://cube.dev/docs/query-format
      const query = {
        dimensions: [
          "Artworks.artist" // 1
        ],
        measures: [
          "Artworks.count" // 2
        ],
        filters: [
          {
            member: "Artworks.classification",
            operator: "equals",
            values: [ "Painting" ] // 3
          }
        ]
      };

      // Let's execute the query via the Cube API...
      cubeApi
        .load(query)
        .then(resultSet => {
          // ...and process the result set.
          // First, let's turn it into an array of two-element arrays with names and counts
          const rows = resultSet.tablePivot().map(function(row) {
            return [ row['Artworks.artist'], parseInt(row['Artworks.count']) ];
          });

          // Second, let's convert it into Google Charts data table.
          // Note that we're passing an array of column names as the first row
          const data = google.visualization.arrayToDataTable([
            [ 'Artist', 'Paintings' ],
            ...rows
          ]);

          // Third, let's specify a few options like pagination
          const options = {
            showRowNumber: true,
            page: 'enable',
            pageSize: 20,
            width: '100%'
          };

          // Eventually, let's render the chart.
          // It will be inserted in place of an HTML element with a known id
          const chart = new google.visualization.Table(document.getElementById('chart__artists'));
          chart.draw(data, options);
        });
    }

    // Function that creates a scatter chart.
    // See the docs to learn more: https://developers.google.com/chart/interactive/docs/gallery/scatterchart
    function drawChartForArtworkYears() {
      // Cube query that will fetch:
      // — production years (1)
      // — acquisition years (2)
      // — count of artworks for each "year created" / "year acquired" pair (3)
      // — but only for those artworks that are labeled as paintings (4)
      // — and have known production year and acquisition year (5, 6)
      const query = {
        dimensions: [
          "Artworks.year", // 1
          "Artworks.yearAcquired" // 2
        ],
        measures: [
          "Artworks.count" // 3
        ],
        filters: [
          {
            member: "Artworks.classification",
            operator: "equals",
            values: [ "Painting" ] // 4
          },
          {
            member: "Artworks.yearAcquired",
            operator: "set" // 5
          },
          {
            member: "Artworks.year",
            operator: "set" // 6
          }
        ]
      };

      cubeApi
        .load(query)
        .then(resultSet => {
          const maxCount = resultSet
            .tablePivot()
            .reduce(function(max, row) {
              return max < row['Artworks.count'] ? row['Artworks.count'] : max;
            }, 0);

          const rows = resultSet.tablePivot().map(function(row) {
            return [
              parseInt(row['Artworks.year']),
              parseInt(row['Artworks.yearAcquired']),
              'point { opacity: ' + (row['Artworks.count'] / maxCount).toFixed(1) + '; }'
            ];
          });

          // Note that the third "column" of data is special.
          // It says we'll be passing styles of the dots on the scatter chart
          const data = google.visualization.arrayToDataTable([
            [ 'Year created', 'Year acquired', { type: 'string', role: 'style' } ],
            ...rows
          ]);

          // The chart type is different, and the options are different as well
          const options = {
            title: 'Year created vs. Year acquired',
            hAxis: { viewWindowMode: 'maximized', title: 'Year created' },
            vAxis: { viewWindowMode: 'maximized', title: 'Year acquired' },
            pointSize: 3,
            height: 500,
            width: '100%',
            legend: 'none'
          };

          new google.visualization
            .ScatterChart(document.getElementById('chart__years'))
            .draw(data, options);
        });
    }
  </script>

  <title>Google Charts Dashboard</title>

  <style>
    .dashboard {
      padding: 64px 5em;
      background-color: #f3f3fb;
      display: grid;
      grid-template-columns: 1fr;
      grid-column-gap: 5em;
    }

    .group {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-column-gap: 5em;
    }
  </style>
</head>

<body>
<div class="dashboard">
  <!-- Charts within the dashboard -->
  <div class="group">
    <div id="chart__artists"></div>
    <div id="chart__years"></div>
  </div>
</div>
 <!-- Load example wrapper -->
 <script type="text/javascript" src="./wrapper.build.js""></script>
</body>
</html>